<template>
  <uni-nav-bar title="购物车" @clickLeft="back"/>
  <view class="cart">
    <view class="content">
      <view class="list" v-for="item in list" :key='index'>
        <view class="left">
          <checkbox-group @change="checkboxChange($event,item.shopId)">
            <checkbox :value="item.id" :checked="item.isChecked"/>
          </checkbox-group>
          <image :src="item.productAvatar" class="img" @click="toDetail(item.productId)"></image>
        </view>
        <view class="center">
          <view class="name">
            {{ item.productName }}
          </view>

        </view>
        <view class="right">
          <view class="price">
            单价￥{{ item.productPrice }}元
          </view>
          <view class="update-count">
            <view class="reduce" @tap="editNum(item.shopId,-1)">
              -
            </view>
            <view class="cart-count">
              {{ item.count }}
            </view>
            <view class="add" @tap="editNum(item.shopId,1)">
              +
            </view>
          </view>
        </view>
      </view>
    </view>
    <div class="empty"></div>
    <!-- 底部导航栏 -->
    <view class="tabbar">
      <view class="all">
        <checkbox-group @change="checkboxChangeAll">
          <checkbox :checked="isAllChecked"/>
          全选
        </checkbox-group>
      </view>
      <view class="totalPrice">
        总价:￥{{ totalPrice }}元
      </view>
      <view class="submitOrder" @tap="submitOrder">
        付款
      </view>
    </view>
  </view>
  <Footer></Footer>
</template>

<script>
import Footer from '../../component/footer/footer.vue'
import list from "@/uni_modules/yulofena-shoppingcart/uni_modules/uview-ui/libs/config/props/list";

export default {
  components: {
    Footer,

  },
  data() {
    return {
      list: [], //列表数据
      isAllChecked: false, //是否全选
      totalPrice: 0, //总价
      userId: "",
    }
  },
  methods: {
    toDetail(id) {
      uni.navigateTo({
        url: '/pages/product/productDetail?id=' + id
      })
    },

    getShopDate() {
      uni.request({
        url: "http://localhost:9999/nbb/Shop/getAll",
        method: 'GET',
        header: {
          'Authorization': uni.getStorageSync('Authorization'),
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          userId: uni.getStorageSync('userId'),
        },
        success: (res) => {
          // console.log(res)
          if (res.data.code == 200) {
            console.log("获取购物车成功");
            this.list = res.data.data
            // console.log(this.list.length)
            for (var i = 0; i < this.list.length; i++) {
              var obj = {
                ...this.list[i],
                count: 1,
                isChecked: false
              };
              this.list[i] = obj
            }
          } else {
            console.log("获取购物车失败");
            console.log(res.data);
          }
        },
        fail() {
          console.log("获取购物车失败");
        }
      })
    },

    setCart() { //计算总价
      let totalPrice = 0
      this.list.forEach(v => {
        if (v.isChecked) {
          totalPrice += v.count * v.productPrice
        }
      })
      this.totalPrice = totalPrice.toFixed(1)
    },

    editNum(id, type) { //编辑数量
      const index = this.list.findIndex(v => v.shopId == id)

      if (this.list[index].count == 1 && type == -1) {
        //弹出删除购物车提醒
        console.log(this.list)
        const list1 = this.list
        console.log(list1[index].shopId)
        let that = this
        uni.showModal({
          title: '是否删除购物车',
          content: '该操作不可恢复',
          success: function (res) {
            if (res.confirm) {
              console.log(list1[index].shopId)
              //开始调用后端的删除接口
              uni.request({
                url: "http://localhost:9999/nbb/Shop/deleteShop",
                method: 'POST',
                header: {
                  'Authorization': uni.getStorageSync('Authorization'),
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                  shopId: list1[index].shopId
                },
                success: (res) => {
                  if (res.data.code === 0) {
                    console.log("删除购物车成功");
                    that.getShopDate()
                  } else {
                    console.log("删除购物车失败");
                    console.log(res.data);
                  }
                },
                fail() {
                  console.log("获取分类失败");
                }
              })

            } else {
              console.log('点击了取消')
            }
          }
        })
      } else {
        this.list[index].count += type
      }
      this.setCart()
    },

    // 全选
    checkboxChangeAll(e) {
      this.isAllChecked = !this.isAllChecked
      this.list.forEach(v => v.isChecked = this.isAllChecked)
      this.setCart()
    },

    // 选择每一项
    checkboxChange: function (e, id) {
      var temp = []
      // 找到被修改的商品对象
      let index = this.list.findIndex(v => v.shopId === id)
      // 选中状态取反
      this.list[index].isChecked = !this.list[index].isChecked

      temp = this.list.every(v => v.isChecked)
      if (temp) {
        this.isAllChecked = true
      } else {
        this.isAllChecked = false
      }
      this.setCart()
    },

    submitOrder() { // 提交购物车订单
      // 判断是否选择购物车商品
      var bol = this.list.every(el => el.isChecked == false)
      if (bol) {
        uni.showToast({
          title: "请选择您的商品",
          icon: "none",
          duration: 2000
        })
      } else {
        var buy = [];
        for (var i = 0; i < this.list.length; i++) {
          if (this.list[i].isChecked !== false) {
            buy.push(this.list[i])
          }
        }
        let data = JSON.stringify(buy);
        uni.navigateTo({
          // url: '/pages/shop/payment?buy='+encodeURIComponent(data),
          url: '/pages/shop/ConfirmThePayment?money= ' + this.totalPrice + '&buys=' + encodeURIComponent(data),
        })
      }
    },
  },
  //实例的生命周期函数，实例创建后被调用
  created() {
    this.userId = uni.getStorageSync('userId');
    this.getShopDate(); //初始化购物车数据
  },
}
</script>
<style lang="scss" scoped>
::v-deep .uni-nav-bar-text {
  font-size: 20px;
}

page {
  background: #F3F3F3;
}

.content {
  width: 670rpx;
  margin: 0 auto 180rpx;
}

// 居中显示
@mixin textCenter {
  display: flex;
  align-items: center;
  justify-content: center;
}

.list {
  width: 672rpx;
  height: 208rpx;
  background: #f9f9f9;
  box-shadow: 0 8rpx 16rpx 0 rgba(83, 66, 49, 0.08);
  border-radius: 24rpx;
  margin-top: 40rpx;
  display: flex;
  justify-content: space-around;
  align-items: center;

  .left {
    display: flex;

    .img {
      width: 136rpx;
      height: 136rpx;
      margin-left: 10rpx;
      border-radius: 8%;
    }
  }

  .center {
    width: 170rpx;

    .name {
      font-size: 30rpx;
      color: #3E3E3E;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .size,
    .count {
      font-size: 22rpx;
      color: #8D8D8D;
    }
  }

  .right {
    .price {
      margin-top: 40rpx;
      font-size: 26rpx;
      margin-left: 40rpx;
    }

    // 加减数量
    .update-count {
      margin-top: 40rpx;
      display: flex;

      .reduce,
      .add {
        width: 40rpx;
        height: 40rpx;
        background: #F1ECE7;
        border-radius: 21.6rpx;
        color: #979797;
        @include textCenter;
        font-size: 50rpx;
      }

      .cart-count {
        width: 72rpx;
        height: 40rpx;
        line-height: 40rpx;
        background: #F1ECE7;
        border-radius: 21.6rpx;
        margin-left: 18rpx;
        margin-right: 18rpx;
        text-align: center;
      }
    }
  }
}

//填充div
.empty {
  height: 100px;
}

// 底部导航
.tabbar {
  width: 100%;
  height: 176rpx;
  background-color: #f3f3f3;
  position: fixed;
  bottom: 150rpx;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-radius: 8% 8%;

  .all {
    font-size: 32rpx;
    color: #3E3E3E;
    letter-spacing: 2.29rpx;
    display: flex;
  }

  .totalPrice {
    font-size: 32rpx;
    color: #3E3E3E;
    letter-spacing: 2.29rpx;
    color: red;
  }

  .submitOrder {
    width: 208rpx;
    height: 80rpx;
    background: #354E44;
    border-radius: 14rpx;
    border-radius: 14rpx;
    font-size: 36rpx;
    color: #FFFFFF;
    letter-spacing: 2.57rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>